from flask import Flask, request, Response, g, jsonify
import sys
import numpy as np
import faiss
import time
import threading
import json
import re
import traceback

from face_embedding.faiss_search import faiss_search_embedding, init_faiss, refresh_faiss, delete_faiss_embedding, add_faiss_embedding

from utils import dbpool_util

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        # db = g._database = sqlite3.connect(DATABASE)
        db = g._database = dbpool_util
    return db

def query_db(query, args=(), one=False):
    # print('sql_s1', query, file=sys.stdout)
    result = get_db().execute_query(query, args)
    return result

@app.route('/face_search', methods=['POST'])
def face_search():
    try:
        groupId = request.form.get("groupId")
        embedding_str = request.form.get("embedding")
        top_n = request.form.get("top_n")
        if top_n is None:
            top_n = 3
        else:
            top_n = int(top_n)
        threshold = request.form.get("threshold")
        if threshold is None:
            threshold = 0.9
        else:
            threshold = float(threshold)
        # print(embedding_str)
        embedding = json.loads(embedding_str)
        error, userCode,I,D = faiss_search_embedding(groupId, embedding, top_n, threshold)
        print(D, I)
        return jsonify({
            'code': 1,
            'data': {
                'userCode': userCode,
                'D': D,
                'I': I
            }
        })
    except Exception as e:
        traceback.print_exc()  ###
        return jsonify({
            'code': -1,
            'message': '异常错误'
        })

@app.route('/face_add', methods=['POST'])
def face_add():
    try:
        groupId = request.form.get("groupId")
        faceId = request.form.get("faceId")
        embedding_str = request.form.get("embedding")
        embeddings = json.loads(embedding_str)
        add_faiss_embedding(groupId, faceId, embeddings)
        return jsonify({
            'code': 1
        })
    except Exception as e:
        traceback.print_exc()  ###
        return jsonify({
            'code': -1,
            'message': '异常错误'
        })

@app.route('/delete_group', methods=['POST'])
def delete_group():
    try:
        groupId = request.form.get("groupId")
        delete_faiss_embedding(groupId)
        return jsonify({
            'code': 1
        })
    except Exception as e:
        traceback.print_exc()  ###
        return jsonify({
            'code': -1,
            'message': '异常错误'
        })

@app.route('/face_reload', methods=['POST'])
def face_reload():
    try:
        groupId = request.form.get("groupId")
        refresh_faiss(groupId, get_db())
        return jsonify({
            'code': 1
        })
    except Exception as e:
        traceback.print_exc()  ###
        return jsonify({
            'code': -1,
            'message': '异常错误'
        })

@app.route('/')
def index():
    return 'faiss service is runing.'

# 初始化faiss
init_faiss(dbpool_util)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=17111)
